﻿Imports System.Xml
Imports System.Data
Imports System.Collections.ObjectModel
Imports System.Collections.Specialized
Imports System.ComponentModel


Partial Public Class NewPetrol
    Public WithEvents Data As PetrolTransactionsList = PetrolTransactionsList.GetList()
    Private WithEvents petrolTrans As PetrolTransactionsClass
    Public WithEvents oWindowList As OpenedWindowList = OpenedWindowList.GetList()
    Private WithEvents oWindow As OpenedWindowClass
    Public WithEvents expenseList As ExpensesList = ExpensesList.GetList()
    Private WithEvents expenseTrans As ExpensesClass


    Dim frmIsDirty As Boolean = False
    Private _pageIsValid As Boolean = True
    Dim editFlag As Integer
    Dim al As New ArrayList
    Dim petrolDB As New IETrackerDataClassesDataContext

    Private Sub NewPetrol_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Dim ied As IEnumerable(Of OpenedWindowClass) = From d In oWindowList Where d.WindowID = Me.Name
        oWindowList.Remove(ied.First)

        If Application.Current.Windows.Count = 1 Then
            Application.Current.Windows(0).Activate()
        End If
    End Sub

    Private Sub NewPetrol_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        If frmIsDirty Then
            If MessageBox.Show("There are unsaved entries. Do you really want to exit?", "Exit", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.No Then
                e.Cancel = True
            End If

        End If
    End Sub

    Private Sub NewPetrol_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        'Data = PetrolTransactionsList.GetList()
        Me.DataContext = Data
        SetupData()
        loadVehicleList()
        LoadSubHeader()
        noSelectedData()
    End Sub

#Region "Change Event Handlers"

    Private Sub HandlePropertyChanged( _
    ByVal sender As Object, _
    ByVal e As PropertyChangedEventArgs)

        Dim propName As String = e.PropertyName
        Dim myCustomer As PetrolTransactionsClass = CType(sender, PetrolTransactionsClass)

        Dim propInfo As System.Reflection.PropertyInfo = _
          GetType(PetrolTransactionsClass).GetProperty(propName)
        Dim value As Object = _
          propInfo.GetValue(myCustomer, Nothing)

    End Sub

    Private Sub Data_CollectionChanged( _
      ByVal sender As Object, _
      ByVal e As NotifyCollectionChangedEventArgs) _
      Handles Data.CollectionChanged

        ' Did you add or remove an item in the collection?
        If e.Action = NotifyCollectionChangedAction.Add Or _
          e.Action = NotifyCollectionChangedAction.Remove Then


            'listBoxPetrol.ScrollIntoView()           

            EnableButtons()
            LoadSubHeader()
        End If
    End Sub

#End Region

#Region "Support Procedures"

    Sub sortData()
        Dim ied As IEnumerable(Of PetrolTransactionsClass) = From d In Data Order By d.TransactionDate Descending
        For Each i In ied
            Data.Remove(i)
            Data.Add(i)
        Next

        Dim iexpense As IEnumerable(Of ExpensesClass) = From d In expenseList Order By d.ExpenseDate Descending
        For Each i In iexpense
            expenseList.Remove(i)
            expenseList.Add(i)
        Next
    End Sub

    Private Sub HookupChangeEventHandlers()
        For Each petrolTrans As PetrolTransactionsClass In Data
            HookupChangeEventHandler(petrolTrans)
        Next
    End Sub

    Private Sub HookupChangeEventHandler(ByVal petrolTrans As PetrolTransactionsClass)
        AddHandler petrolTrans.PropertyChanged, _
          AddressOf HandlePropertyChanged
    End Sub

    Public Function FilterCompletedTasks(ByVal t As Object) As Boolean
        Dim _task As New PetrolTransactionsClass
        _task = t
        Return _task.VehicleDetails.ToUpper.Contains(searchBox.Text.ToUpper)
    End Function
#End Region

#Region "Ribbon Action Event Handlers"

    Private Sub RibbonButtonCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonCancel.Click
        If editFlag = HelperClass.EditMode.Add Then
            HelperClass.ClearTextBox(gridPetrolDetails)
            HelperClass.ClearComboBox(gridPetrolDetails)
            DatePickerPetrol.SelectedDate = Nothing
            noSelectedData()
        ElseIf editFlag = HelperClass.EditMode.Edit Then

            If listBoxPetrol.SelectedIndex >= 0 Then
                With listBoxPetrol.SelectedValue
                    TextBoxAmount.Text = .TransactionAmount
                    DatePickerPetrol.SelectedDate = .TransactionDate
                    TextBoxDistance.Text = .TransactionDistance
                    comboboxVehicle.SelectedValue = .VehicleID
                    TextBoxLitres.Text = .TransactionLitres
                    TextBoxAmountPerLitre.Text = .TransactionAmountPerLitre
                    TextBoxComment.Text = .Comment
                End With

            End If
            frmIsDirty = True
            setButtonProperties()
        End If
    End Sub

    Private Sub RibbonButtonDelete_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonDelete.Click
        Dim index As Integer = listBoxPetrol.SelectedIndex
        If index >= 0 Then
            Try
                Dim warningString As String = "Do you really want to delete this transaction?" & ControlChars.Lf & listBoxPetrol.SelectedItem.transactiondetails
                If System.Windows.MessageBox.Show(warningString, "Delete Transaction", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    Dim selectedPetrolItem As Integer = listBoxPetrol.SelectedValue.transactionid

                    Dim deleteFromPetrol = From petrol In petrolDB.Petrols.AsEnumerable _
                                                     Where petrol.TransactionID = selectedPetrolItem
                    petrolDB.Petrols.DeleteOnSubmit(deleteFromPetrol.First)

                    Dim deleteFromTransaction = From trans In petrolDB.Transactions _
                                                Where trans.TransactionID = selectedPetrolItem
                    petrolDB.Transactions.DeleteOnSubmit(deleteFromTransaction.First)


                    RemoveHandler Data.Item(index).PropertyChanged, AddressOf HandlePropertyChanged

                    Dim iPetrolTransactionClass As IEnumerable(Of PetrolTransactionsClass) = From d In Data Where d.TransactionID = selectedPetrolItem
                    Data.Remove(iPetrolTransactionClass.First)

                    Dim iExpensesClass As IEnumerable(Of ExpensesClass) = From d In expenseList Where d.ExpenseId = selectedPetrolItem
                    expenseList.Remove(iExpensesClass.First)
                    petrolDB.SubmitChanges()


                    ' Anything left in the list? If so
                    ' reset the list box. Otherwise, 
                    ' clear out the text box:
                    If Data.Count > 0 Then
                        ResetListBox()
                        HelperClass.ClearTextBox(gridPetrolDetails)
                        HelperClass.ClearComboBox(gridPetrolDetails)
                        DatePickerPetrol.SelectedDate = Nothing
                        noSelectedData()
                    End If
                End If

            Catch ex As Exception
                MessageBox.Show("Error encountered while deleting the record." & ControlChars.Lf & ControlChars.Lf & ex.message.tostring, "Delete Error", MessageBoxButton.OK, MessageBoxImage.Error)
            End Try
        End If

    End Sub

    Private Sub RibbonButtonNew_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonNew.Click
        mainOverlay.Visibility = Visibility.Collapsed
        editFlag = HelperClass.EditMode.Add

        listBoxPetrol.SelectedIndex = -1
        HelperClass.ClearTextBox(gridPetrolDetails)
        HelperClass.ClearComboBox(gridPetrolDetails)
        DatePickerPetrol.SelectedDate = Nothing

        frmIsDirty = True
        setButtonProperties()
    End Sub


    Private Sub RibbonButtonSave_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles RibbonButtonSave.Click
        pageIsValid(DatePickerPetrol.Name, EntryValidation.ValidateDatePicker(DatePickerPetrol))
        pageIsValid(comboboxVehicle.Name, EntryValidation.ValidateCombo(comboboxVehicle))
        pageIsValid(TextBoxAmount.Name, EntryValidation.ValidateText(TextBoxAmount))


        If _pageIsValid Then
            Try
                If editFlag = HelperClass.EditMode.Add Then
                    Dim saveNewPetrolTransaction As New Petrol
                    Dim saveNewTransaction As New Transaction

                    With saveNewTransaction
                        .TransactionAmount = TextBoxAmount.Text
                        .TransactionDate = DatePickerPetrol.Text
                        .TransactionTypeID = 1
                        .Comment = TextBoxComment.Text
                    End With
                    petrolDB.Transactions.InsertOnSubmit(saveNewTransaction)
                    petrolDB.SubmitChanges()

                    With saveNewPetrolTransaction
                        .Date = DatePickerPetrol.Text
                        .Distance = TextBoxDistance.Text
                        .Vehicle = comboboxVehicle.SelectedValue
                        .Litres = TextBoxLitres.Text
                        .Amount = TextBoxAmount.Text
                        .AmountPerLitre = TextBoxAmountPerLitre.Text
                        .TransactionID = saveNewTransaction.TransactionID
                    End With

                    petrolDB.Petrols.InsertOnSubmit(saveNewPetrolTransaction)
                    petrolDB.SubmitChanges()

                    petrolTrans = New PetrolTransactionsClass(DatePickerPetrol.Text _
                                                              , comboboxVehicle.SelectedValue _
                                                              , TextBoxDistance.Text _
                                                              , TextBoxLitres.Text _
                                                              , TextBoxAmount.Text _
                                                              , TextBoxAmountPerLitre.Text _
                                                              , FormatDateTime(DatePickerPetrol.Text.ToString, DateFormat.ShortDate) & " - " & FormatCurrency(TextBoxAmount.Text) _
                                                              , comboboxVehicle.SelectedItem.RegoNumber & " - " & comboboxVehicle.SelectedItem.vehicle.Make & "/" & comboboxVehicle.SelectedItem.vehicle.Model _
                                                              , comboboxVehicle.SelectedItem.vehicle.image _
                                                              , saveNewTransaction.TransactionID _
                                                              , TextBoxComment.Text)
                    HookupChangeEventHandler(petrolTrans)
                    Data.Add(petrolTrans)

                    expenseTrans = New ExpensesClass("Petrol", TextBoxAmount.Text, DatePickerPetrol.Text, saveNewTransaction.TransactionID, 1, 0, TextBoxComment.Text)
                    expenseList.Add(expenseTrans)
                    frmIsDirty = False
                    setButtonProperties()
                    sortData()
                    editFlag = HelperClass.EditMode.Edit

                    Dim ctr As Integer = 0
                    For Each item In Data
                        If item.TransactionID = saveNewTransaction.TransactionID Then
                            Exit For
                        End If
                        ctr += 1
                    Next

                    listBoxPetrol.SelectedIndex = ctr

                ElseIf editFlag = HelperClass.EditMode.Edit Then
                    Dim selectedPetrolItem As Integer = listBoxPetrol.SelectedValue.transactionid '.petrol.mainid
                    Dim editTransaction = From petrol In petrolDB.Petrols _
                                 Join trans In petrolDB.Transactions _
                                 On petrol.TransactionID Equals trans.TransactionID _
                                 Where petrol.TransactionID = selectedPetrolItem

                    With editTransaction.First
                        .petrol.Amount = TextBoxAmount.Text
                        .petrol.Date = DatePickerPetrol.Text
                        .petrol.Distance = TextBoxDistance.Text
                        .petrol.Vehicle = comboboxVehicle.SelectedValue
                        .petrol.Litres = TextBoxLitres.Text
                        .petrol.AmountPerLitre = TextBoxAmountPerLitre.Text

                        .trans.TransactionDate = DatePickerPetrol.Text
                        .trans.TransactionAmount = TextBoxAmount.Text
                        .trans.Comment = TextBoxComment.Text
                    End With
                    petrolDB.SubmitChanges()

                    'reflect changes in list                    
                    With Data.Where(Function(x) x.TransactionID = listBoxPetrol.SelectedValue.transactionid).First
                        .TransactionAmount = TextBoxAmount.Text
                        .TransactionDate = DatePickerPetrol.Text
                        .TransactionDistance = TextBoxDistance.Text
                        .VehicleID = comboboxVehicle.SelectedValue
                        .TransactionLitres = TextBoxLitres.Text
                        .TransactionAmountPerLitre = TextBoxAmountPerLitre.Text

                        .TransactionDetails = FormatDateTime(DatePickerPetrol.SelectedDate, DateFormat.ShortDate) & " - " & FormatCurrency(TextBoxAmount.Text)
                        .VehicleDetails = comboboxVehicle.SelectedItem.RegoNumber & " - " & comboboxVehicle.SelectedItem.vehicle.Make & "/" & comboboxVehicle.SelectedItem.vehicle.Model
                        .Image = comboboxVehicle.SelectedItem.image
                        .Comment = TextBoxComment.Text
                    End With

                    With expenseList.Where(Function(x) x.ExpenseId = listBoxPetrol.SelectedValue.transactionid).First
                        .ExpenseAmount = TextBoxAmount.Text
                        .ExpenseDate = DatePickerPetrol.Text
                        .ExpenseType = "Petrol"
                    End With

                End If

                frmIsDirty = False
                setButtonProperties()
                LoadSubHeader()


            Catch ex As Exception
                MessageBox.Show("Error encountered while saving the record." & ControlChars.Lf & ControlChars.Lf & ex.message.tostring, "Save Error", MessageBoxButton.OK, MessageBoxImage.Error)
                With listBoxPetrol.SelectedValue
                    TextBoxAmount.Text = .TransactionAmount
                    DatePickerPetrol.SelectedDate = .TransactionDate
                    TextBoxDistance.Text = .TransactionDistance
                    comboboxVehicle.SelectedValue = .VehicleID
                    TextBoxLitres.Text = .TransactionLitres
                    TextBoxAmountPerLitre.Text = .TransactionAmountPerLitre
                    TextBoxComment.Text = .Comment
                End With
            End Try
        Else
            MessageBox.Show("There are invalid entries. Edit items before saving.", "Save Error", MessageBoxButton.OK, MessageBoxImage.Error)
        End If
    End Sub

#End Region

#Region "Set Default"

    Private Sub ResetListBox()
        listBoxPetrol.SelectedIndex = 0
        listBoxPetrol.Focus()
    End Sub

    Private Sub SetupData()
        HookupChangeEventHandlers()

        If Data.Count > 0 Then
            ResetListBox()
        End If
    End Sub

    Private Sub EnableButtons()
        Dim enabled As Boolean = Data.Count > 0
        RibbonButtonCancel.IsEnabled = enabled
        RibbonButtonDelete.IsEnabled = enabled
        RibbonButtonSave.IsEnabled = enabled
    End Sub

    Sub setButtonProperties()
        If frmIsDirty Then
            RibbonButtonSave.IsEnabled = True
            RibbonButtonCancel.IsEnabled = True
            RibbonButtonDelete.IsEnabled = True
            'RibbonButtonNew.IsEnabled = False
        Else
            RibbonButtonSave.IsEnabled = False
            RibbonButtonCancel.IsEnabled = False
            RibbonButtonDelete.IsEnabled = False
            'RibbonButtonNew.IsEnabled = True
        End If
    End Sub

    Sub pageIsValid(ByVal sender As String, ByVal isValid As Boolean)
        Dim inArray As Boolean = False
        For i = 0 To al.Count - 1
            If al.Item(i) = sender Then
                If isValid Then
                    al.Remove(Trim(sender))
                End If
                inArray = True
                Exit For
            End If
        Next
        If Not inArray Then
            If Not isValid Then
                al.Add(Trim(sender))
            End If
        End If
        If al.Count > 0 Then
            _pageIsValid = False
        Else
            _pageIsValid = True
        End If
    End Sub

    Sub LoadSubHeader()
        Dim petrolSummary = From pSum In petrolDB.Petrols.AsEnumerable Order By pSum.Date Descending

        LabelFirstTransaction.Content = Data.Last.TransactionDate
        LabelLatestTransaction.Content = Data.First.TransactionDate
        LabelTotalTransaction.Content = "Total : " & FormatCurrency(Data.Sum(Function(x) x.TransactionAmount))
        LabelTotalDistance.Content = " @ " & Data.Sum(Function(x) x.TransactionDistance).ToString("N2") & " kms"

        If Data.Count > 1 Then
            ExpanderText.Text = Data.Count & " records found"
        Else
            ExpanderText.Text = Data.Count & " record found"
        End If

    End Sub

    Sub loadVehicleList()
        Dim vehicleList = From vehicle In petrolDB.Vehicles.AsEnumerable _
                          Select vehicle, vehicle.RegoNumber, image = IIf(IO.File.Exists("../.." & vehicle.image) Or IO.File.Exists(vehicle.image), vehicle.image, "../../Resources/Classic_66_32.png"), vehicleDDLItems = vehicle.RegoNumber, MainId = vehicle.MainId

        comboboxVehicle.ItemsSource = vehicleList
        comboboxVehicle.SelectedValuePath = "MainId"
        comboboxVehicle.SelectedIndex = -1
    End Sub

    Sub noSelectedData()
        listBoxPetrol.SelectedIndex = -1
        frmIsDirty = False
        setButtonProperties()
        mainOverlay.Visibility = Visibility.Visible
    End Sub
#End Region

#Region "Control Event Handlers"
    Private Sub TextBoxComment_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxComment.TextChanged
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub TextBoxAmountPerLitre_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxAmountPerLitre.TextChanged
        pageIsValid(TextBoxAmountPerLitre.Name, EntryValidation.ValidateIsNumeric(TextBoxAmountPerLitre, False))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub TextBoxAmount_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxAmount.TextChanged
        pageIsValid(TextBoxAmount.Name, EntryValidation.ValidateIsNumeric(TextBoxAmount, True))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub TextBoxLitres_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxLitres.TextChanged
        pageIsValid(TextBoxLitres.Name, EntryValidation.ValidateIsNumeric(TextBoxLitres, False))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub TextBoxDistance_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBoxDistance.TextChanged
        pageIsValid(TextBoxDistance.Name, EntryValidation.ValidateIsNumeric(TextBoxDistance, False))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub comboboxVehicle_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles comboboxVehicle.SelectionChanged
        pageIsValid(comboboxVehicle.Name, EntryValidation.ValidateCombo(comboboxVehicle))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub DatePickerPetrol_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles DatePickerPetrol.SelectedDateChanged
        pageIsValid(DatePickerPetrol.Name, EntryValidation.ValidateDatePicker(DatePickerPetrol))
        frmIsDirty = True
        setButtonProperties()
    End Sub

    Private Sub listBoxPetrol_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxPetrol.SelectionChanged
        If listBoxPetrol.SelectedIndex >= 0 Then
            With listBoxPetrol.SelectedValue
                DatePickerPetrol.SelectedDate = .TransactionDate
                comboboxVehicle.SelectedValue = .VehicleID
                TextBoxDistance.Text = .TransactionDistance
                TextBoxLitres.Text = .TransactionLitres
                TextBoxAmount.Text = .TransactionAmount
                TextBoxAmountPerLitre.Text = .TransactionAmountPerLitre
                TextBoxComment.Text = .Comment
            End With

            mainOverlay.Visibility = Visibility.Collapsed
            editFlag = HelperClass.EditMode.Edit
            frmIsDirty = True
            setButtonProperties()
        Else
            HelperClass.ClearTextBox(gridPetrolDetails)
            HelperClass.ClearComboBox(gridPetrolDetails)
            DatePickerPetrol.SelectedDate = Nothing
        End If
    End Sub

    Private Sub searchBox_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles searchBox.GotFocus
        If searchBox.Text = "Search" Then
            searchBox.Text = Nothing
        End If
    End Sub

    Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles searchBox.TextChanged
        If Not listBoxPetrol Is Nothing Then
            Dim icview As ICollectionView = CollectionViewSource.GetDefaultView(Data)
            'If icview.Filter Is Nothing Then
            icview.Filter = New Predicate(Of Object)(AddressOf FilterCompletedTasks)
            'Else
            'icview.Filter = Nothing
            'End If
        End If
    End Sub

#End Region

   
    
    
End Class

